package com.aliyun.messagemgt.application.service.Impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.messagemgt.common.dto.send.PushChannelInfo;
import com.aliyun.messagemgt.common.annotation.PagingAnnotation;
import com.aliyun.messagemgt.application.service.MsgSourceService;
import com.aliyun.messagemgt.application.service.OperateLogService;
import com.aliyun.messagemgt.util.DateUtil;
import com.aliyun.messagemgt.common.constants.SmsQuotaConstant;
import com.aliyun.messagemgt.common.enums.*;
import com.aliyun.messagemgt.common.errorcode.CommonErrorCode;
import com.aliyun.messagemgt.common.exceptions.BaseException;
import com.aliyun.messagemgt.domain.repository.*;
import com.aliyun.messagemgt.dto.*;
import com.aliyun.messagemgt.dto.base.FourAObjectEntity;
import com.aliyun.messagemgt.dto.query.BaseMessageSourceQuery;
import com.aliyun.messagemgt.dto.query.MsgQuery;
import com.aliyun.messagemgt.dto.vo.DepVo;
import com.aliyun.messagemgt.dto.vo.MessageTypeVO;
import com.aliyun.messagemgt.dto.vo.MsgSourceVO;
import com.aliyun.messagemgt.entities.BaseMessageSourceEntity;
import com.aliyun.messagemgt.entities.MsgSourceChannel;
import com.aliyun.messagemgt.repository.mappers.MsgSourceChannelMapper;
import com.aliyun.messagemgt.repository.mappers.MsgSourceMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Administrator
 */
@Service
public class MsgSourceServiceImpl implements MsgSourceService {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final String DAY_START = " 00:00:00";

    private static final String DAY_END = " 23:59:59";

    private Logger logger = LoggerFactory.getLogger(MsgSourceServiceImpl.class);
    @Autowired
    private MsgSourceRepository msgSourceMapper;
    @Autowired
    private SmsQuotaRepository smsQuotaMapper;
    @Autowired
    private SmsQuotaConfigRepository smsQuotaDefaultConfigMapper;
    @Autowired
    private MessageTemplateRepository messageTemplateMapper;
    @Autowired
    private OperateLogService operateLogService;
    @Autowired
    private PushChannelRepository pushChannelRepository;

    @Autowired
    private MsgSourceChannelMapper msgSourceChannelMapper;

    @Autowired
    private MsgSourceMapper msgMapper;

    @Override
    public int countMsgSouece(MsgQuery msgQuery) {

        if (StringUtils.isNotBlank(msgQuery.getCreTimeStart())) {
            StringBuilder creTimeStart = new StringBuilder(msgQuery.getCreTimeStart());
            creTimeStart.append(DAY_START);
            msgQuery.setCreTimeStart(creTimeStart.toString());
        }
        if (StringUtils.isNotBlank(msgQuery.getCreTimeEnd())) {
            StringBuilder creTimeEnd = new StringBuilder(msgQuery.getCreTimeEnd());
            creTimeEnd.append(DAY_END);
            msgQuery.setCreTimeEnd(creTimeEnd.toString());
        }
        return msgSourceMapper.countMsgSouece(msgQuery);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addMsgSource(MsgAdd msgAdd) {
        Integer codeData = msgSourceMapper.queryByCode(msgAdd);
        if (codeData > 0) {
            throw new BaseException(CommonErrorCode.CODING_REPEAT);
        }
        int i = 0;
        MsgSource msgSource = new MsgSource();
        //设置消息源有效期
        setLimitDate(msgAdd);
        List<Long> pushChannelIds = msgAdd.getPushChannelIds();
        Date endTime = null;
        Date startTime = null;
        endTime = DateUtil.getFormatedDateTime(msgAdd.getEndTime());
        startTime = DateUtil.getFormatedDateTime(msgAdd.getStartTime());
        BeanUtils.copyProperties(msgAdd, msgSource);
        msgSource.setStartTime(startTime);
        msgSource.setEndTime(endTime);
        // 请求里的管理员
        List<FourAObjectEntity> ownerRequest = msgAdd.getOwnerRequest();
        String owner = JSON.toJSONString(ownerRequest);
        msgSource.setOwner(owner);
        int count = 0;
        if (null != msgAdd.getMsgSourceId()) {
            count = msgSourceMapper.selectCountByNameExceptSelf(msgAdd);
            if (count > 0) {
                throw new BaseException(CommonErrorCode.COMMON_MSGSCOURCE_NAME_REPEAT_ERROR);
            }
            i = msgSourceMapper.modMsgSource(msgSource);
        } else {
            // 判断是否有同名消息源
            count = msgSourceMapper.selectCountByName(msgAdd.getSourceName());
            if (count > 0) {
                throw new BaseException(CommonErrorCode.COMMON_MSGSCOURCE_NAME_REPEAT_ERROR);
            }
            /*String sourecId = generateMsgSourceId();
            msgSource.setSourceCode(sourecId);*/
            i = msgSourceMapper.addMsgSource(msgSource);
        }
//        if (count < 1) {
//            operateLogService.insertOperateLog(MsgAdd, CommonErrorCode.FAIL_UPDATE_MSGTEMPLATE.errName(), failMsg);
//            throw new BaseException(CommonErrorCode.FAIL_UPDATE_MSGTEMPLATE);
//        }
        msgAdd.setMsgSourceId(msgSource.getMsgSourceId());

        //是否为短信消息源，是短信消息源的话，不管什么状态，添加默认配额
        if (ChannelTypeEnum.DYSMS.getType().equals(msgAdd.getPushChannelType())) {
            initSmsQuota(msgSource);
        }
        if (pushChannelIds == null && pushChannelIds.size() < 1) {
            return i;
        }
        QueryWrapper<MsgSourceChannel> query = new QueryWrapper<>();
        query.eq("msg_source_id", msgAdd.getMsgSourceId());
        query.eq("is_deleted", "N");
        List<MsgSourceChannel> msgSourceChannels = msgSourceChannelMapper.selectList(query);


        for (Long pushChannelId : pushChannelIds) {
            msgSourceChannels.removeIf(sourceChannel -> pushChannelId.equals(sourceChannel.getPushChannelId()));
        }


        for (MsgSourceChannel msgSourceChannel : msgSourceChannels) {
            msgSourceChannel.setIsDeleted("Y");
            msgSourceChannelMapper.updateById(msgSourceChannel);
        }
        for (Long pushChannelId : pushChannelIds) {
            QueryWrapper<MsgSourceChannel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("push_channel_id", pushChannelId);
            queryWrapper.eq("msg_source_id", msgAdd.getMsgSourceId());
            queryWrapper.eq("is_deleted", "N");
            List<MsgSourceChannel> msgSourceChannels1 = msgSourceChannelMapper.selectList(queryWrapper);
            if (msgSourceChannels1.size() < 1) {
                MsgSourceChannel msgSourceChannel = new MsgSourceChannel();
                BeanUtils.copyProperties(msgAdd, msgSourceChannel);
                msgSourceChannel.setPushChannelId(pushChannelId);
                msgSourceChannelMapper.insert(msgSourceChannel);
            }
        }

        return i;
    }

    /**
     * 设置消息源有效期：开始/截止日期设置消息源有效期：开始/截止日期
     */
    public void setLimitDate(MsgAdd msgAdd) {
        Integer sourceType = msgAdd.getSourceType();
        SourceTypeEnum sourceTypeEnum = SourceTypeEnum.valueofType(sourceType);
        Date current = DateUtil.getCurrnetDate();
        Calendar c = Calendar.getInstance();
        switch (sourceTypeEnum) {
            case NO_LIMIT:
                break;
            case ONE_YEAR:
                c.setTime(current);
                //年份加一年
                c.add(Calendar.YEAR, 1);
                msgAdd.setStartTime(DateUtil.getFormatedDateTime(current));
                msgAdd.setEndTime(DateUtil.getFormatedDateTime(c.getTime()));
                break;
            case ONE_MONTH:
                c.setTime(current);
                //加一个月
                c.add(Calendar.MONTH, 1);
                msgAdd.setStartTime(DateUtil.getFormatedDateTime(current));
                msgAdd.setEndTime(DateUtil.getFormatedDateTime(c.getTime()));
                break;
            case ONE_WEEK:
                c.setTime(current);
                //加一周
                c.add(Calendar.WEEK_OF_MONTH, 1);
                msgAdd.setStartTime(DateUtil.getFormatedDateTime(current));
                msgAdd.setEndTime(DateUtil.getFormatedDateTime(c.getTime()));
                break;
            case ONE_DAY:
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(current);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                Date zero = calendar.getTime();
                msgAdd.setStartTime(DateUtil.getFormatedDateTime(zero));
                calendar.setTime(current);
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                Date zero1 = calendar.getTime();
                msgAdd.setEndTime(DateUtil.getFormatedDateTime(zero1));
                break;
            case CUSTOM:
                break;
            default:
                break;
        }
    }

    /**
     * 为短信消息源设置默认配额
     *
     * @param msgSource 消息源
     */
    private void initSmsQuota(MsgSource msgSource) {
        //先查询是否存在生效的消息源
        MsgQuery msgQuery = new MsgQuery();
        msgQuery.setMsgSourceId(msgSource.getMsgSourceId());
        MsgSourceVO msgSourceVO = msgSourceMapper.queryMsgSourceDetail(msgQuery);
        if (msgSourceVO.getSourceCode() != null) {
            SmsQuota exist = smsQuotaMapper.queryQuotaByMsgSourceIdAndStatus(msgSourceVO.getSourceCode(), SmsQuotaConstant.EFFECTIVE_STATUS_SHENGXIAO);
            if (exist != null) {
                logger.info("已存在生效的短信配额设置");
                return;
            }
        }
        logger.info("为消息源：{} 配置默认短信配额", msgSource.getSourceCode());
        SmsQuota smsQuota = new SmsQuota();
        //读取系统设置中的短信配额，短信配额类型
        SmsQuotaDefaultConfig config = smsQuotaDefaultConfigMapper.queryConfig(null);
        smsQuota.setMsgSourceId(msgSource.getSourceCode())
                .setQuotaType(config.getQuotaType())
                .setQuota(config.getQuota())
                //这里直接设置生效
                .setEffectiveStatus(SmsQuotaConstant.EFFECTIVE_STATUS_SHENGXIAO)
                .setEffectiveType(SmsQuotaConstant.EFFECTIVE_TYPE_NOW)
                .setEffectiveBeginTime(msgSource.getStartTime())
                .setCreateTime(new Date())
                .setCreateUserName(msgSource.getUserName())
                .setUpdateUserCode(msgSource.getUserId())
                .setUpdateTime(new Date())
                .setUpdateUserName(msgSource.getUserName());
        int result = smsQuotaMapper.insert(smsQuota);
        if (result < 1) {
            throw new RuntimeException("配置短信消息源默认配额失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveMsgSource(MsgAdd msgAdd) {
        Integer codeData = msgSourceMapper.queryByCode(msgAdd);
        if (codeData > 0) {
            throw new BaseException(CommonErrorCode.CODING_REPEAT);
        }
        int i = 0;
        MsgSource msgSource = new MsgSource();
        List<Long> pushChannelIds = msgAdd.getPushChannelIds();
        //设置消息源有效期
        setLimitDate(msgAdd);
        Date endTime = null;
        Date startTime = null;
        endTime = DateUtil.getFormatedDateTime(msgAdd.getEndTime());
        startTime = DateUtil.getFormatedDateTime(msgAdd.getStartTime());
        BeanUtils.copyProperties(msgAdd, msgSource);
        msgSource.setStartTime(startTime);
        msgSource.setEndTime(endTime);
        // 请求里的管理员
        List<FourAObjectEntity> ownerRequest = msgAdd.getOwnerRequest();
        String owner = JSON.toJSONString(ownerRequest);
        msgSource.setOwner(owner);
        int count = 0;
        if (null != msgAdd.getMsgSourceId()) {
            count = msgSourceMapper.selectCountByNameExceptSelf(msgAdd);
            if (count > 0) {
                throw new BaseException(CommonErrorCode.COMMON_MSGSCOURCE_NAME_REPEAT_ERROR);
            }
            i = msgSourceMapper.modMsgSource(msgSource);
            //进行发送任务与多渠道的关联
            QueryWrapper<MsgSourceChannel> query = new QueryWrapper<>();
            query.eq("msg_source_id", msgAdd.getMsgSourceId());
            query.eq("is_deleted", "N");
            List<MsgSourceChannel> msgSourceChannels = msgSourceChannelMapper.selectList(query);

            if (pushChannelIds != null && pushChannelIds.size() > 0) {
                for (Long pushChannelId : pushChannelIds) {
                    for (int x = 0; x < msgSourceChannels.size(); x++) {
                        if (pushChannelId.equals(msgSourceChannels.get(x).getPushChannelId())) {
                            msgSourceChannels.remove(msgSourceChannels.get(x));
                        }
                    }
                }

                for (MsgSourceChannel msgSourceChannel : msgSourceChannels) {
                    msgSourceChannel.setIsDeleted("Y");
                    msgSourceChannelMapper.updateById(msgSourceChannel);
                }
                for (Long pushChannelId : pushChannelIds) {
                    QueryWrapper<MsgSourceChannel> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("push_channel_id", pushChannelId);
                    queryWrapper.eq("msg_source_id", msgAdd.getMsgSourceId());
                    queryWrapper.eq("is_deleted", "N");
                    List<MsgSourceChannel> msgSourceChannels1 = msgSourceChannelMapper.selectList(queryWrapper);
                    if (msgSourceChannels1 == null && msgSourceChannels.size() < 1) {
                        MsgSourceChannel msgSourceChannel = new MsgSourceChannel();
                        BeanUtils.copyProperties(msgAdd, msgSourceChannel);
                        msgSourceChannel.setPushChannelId(pushChannelId);
                        msgSourceChannelMapper.insert(msgSourceChannel);
                    }
                }
            }
        } else {
            // 判断是否有同名消息源
            count = msgSourceMapper.selectCountByName(msgAdd.getSourceName());
            if (count > 0) {
                throw new BaseException(CommonErrorCode.COMMON_MSGSCOURCE_NAME_REPEAT_ERROR);
            }
            /*String sourecId = generateMsgSourceId();
            msgSource.setSourceCode(sourecId);*/
            i = msgSourceMapper.addMsgSource(msgSource);
            msgAdd.setMsgSourceId(msgSource.getMsgSourceId());
            //进行发送任务与多渠道的关联
            if (pushChannelIds != null && pushChannelIds.size() > 0) {
                for (Long pushChannelId : pushChannelIds) {
                    MsgSourceChannel msgSourceChannel = new MsgSourceChannel();
                    BeanUtils.copyProperties(msgAdd, msgSourceChannel);
                    msgSourceChannel.setPushChannelId(pushChannelId);
                    msgSourceChannelMapper.insert(msgSourceChannel);
                }
            }
        }

        //是否为短信消息源，是短信消息源的话，不管什么状态，添加默认配额
        if (ChannelTypeEnum.DYSMS.getType().equals(msgAdd.getPushChannelType())) {
            initSmsQuota(msgSource);
        }
        //消息源绑定消息模板
//        msgSourceBindTemplate(msgAdd.getTemplateId(), msgSource.getSourceId());

        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer modMsgSource(MsgAdd msgAdd) {
        Integer data = msgSourceMapper.queryByCode(msgAdd);
        if (data > 0) {
            throw new BaseException(CommonErrorCode.CODING_REPEAT);
        }
        MsgSource msgSource = new MsgSource();
        msgSource.setMsgSourceId(msgAdd.getMsgSourceId());
        return msgSourceMapper.modMsgSource(msgSource);
    }

    @Override
    @PagingAnnotation
    public Page<MsgSourceVO> listMsgSource(MsgQuery msgQuery) {
        Page<MsgSourceVO> msgSourceVOs = msgSourceMapper.list(msgQuery);
        /*if (msgSourceVOs.size() > 0) {
            for (MsgSourceVO msgSourceVO : msgSourceVOs) {
                if (AuditStatusEnum.UNAUDITED.getValue().equals(msgSourceVO.getAuditStatus())) {
                    msgSourceVO.setAuditStatusReturn(AuditStatusEnum.UNAUDITED.getState());
                }
                if (AuditStatusEnum.AUDIT_NOPASS.getValue().equals(msgSourceVO.getAuditStatus())) {
                    msgSourceVO.setAuditStatusReturn(AuditStatusEnum.AUDIT_NOPASS.getState());
                }
                if (AuditStatusEnum.AUDIT_PASS.getValue().equals(msgSourceVO.getAuditStatus())) {
                    msgSourceVO.setAuditStatusReturn(AuditStatusEnum.AUDIT_PASS.getState());
                }
                if (AuditStatusEnum.UNCOMMITTED.getValue().equals(msgSourceVO.getAuditStatus())) {
                    msgSourceVO.setAuditStatusReturn(AuditStatusEnum.UNCOMMITTED.getState());
                }
                List<FourAObjectEntity> ownerVos = JSON.parseArray(msgSourceVO.getOwner(), FourAObjectEntity.class);
                if (!CollectionUtils.isEmpty(ownerVos)) {
                    msgSourceVO.setDataPrivilege(0);
                    for (FourAObjectEntity fourAObjectEntity : ownerVos) {
                        if (null!=msgQuery.getUserId() && msgQuery.getUserId().equals(fourAObjectEntity.getKey())) {
                            msgSourceVO.setDataPrivilege(1);
                            break;
                        }
                    }
                    // TODO 暂时为测试加上
                    if (msgQuery.getRole() == 1) {
                        msgSourceVO.setDataPrivilege(1);
                    }
                } else {
                    msgSourceVO.setDataPrivilege(0);
                    // TODO 暂时为测试加上
                    if (msgQuery.getRole() == 1) {
                        msgSourceVO.setDataPrivilege(1);
                    }
                }
            }
        }*/
        return msgSourceVOs;
    }

    @Override
    public MsgSourceVO msgSourceDetail(MsgQuery msgQuery) {
        MsgSourceVO msgSourceVO = msgSourceMapper.queryMsgSourceDetail(msgQuery);
//        if (msgSourceVO.getPushChannelType()==4){
//            msgSourceVO.setSourceId("7b2af0203a714853bd86397676e61085");
//        }
        return msgSourceVO;
    }

    @Override
    @PagingAnnotation
    public PageInfo<MsgSourceVO> queryMsgList(MsgQuery msgQuery) {
        if (StringUtils.isNotBlank(msgQuery.getCreTimeStart())) {
            StringBuilder creTimeStart = new StringBuilder(msgQuery.getCreTimeStart());
            creTimeStart.append(DAY_START);
            msgQuery.setCreTimeStart(creTimeStart.toString());
        }
        if (StringUtils.isNotBlank(msgQuery.getCreTimeEnd())) {
            StringBuilder creTimeEnd = new StringBuilder(msgQuery.getCreTimeEnd());
            creTimeEnd.append(DAY_END);
            msgQuery.setCreTimeEnd(creTimeEnd.toString());
        }
        List<MsgSourceVO> msgSourceVOs = msgSourceMapper.queryMsgList(msgQuery);
        PageInfo pageInfo = new PageInfo(msgSourceVOs);
        if (null != msgSourceVOs && msgSourceVOs.size() > 0) {
            for (MsgSourceVO msgSourceVO : msgSourceVOs) {
                Integer pushChannelType = msgSourceVO.getPushChannelType();
                for (ChannelTypeEnum channelTypeEnum : ChannelTypeEnum.values()) {
                    if (pushChannelType.equals(channelTypeEnum.getType())) {
                        msgSourceVO.setPushChannelTypeName(channelTypeEnum.getName());
                    }
                }

                if (msgSourceVO.getPushResultCode().equals(PushResultEnum.PUSH_SUCCESS.getErrorCode())) {
                    msgSourceVO.setPushResultCodeReturn(PushResultEnum.PUSH_SUCCESS.getDescription());
                }
                if (!msgSourceVO.getPushResultCode().equals(PushResultEnum.PUSH_SUCCESS.getErrorCode())) {
                    msgSourceVO.setPushResultCodeReturn(PushResultEnum.PUSH_ERROR.getDescription());
                }
                if (MsgSourceEnum.API.getValue().equals(msgSourceVO.getMsgSourceType())) {
                    msgSourceVO.setMsgSourceTypeName(MsgSourceEnum.API.getTypeName());
                }
                if (MsgSourceEnum.SMARTPUSH.getValue().equals(msgSourceVO.getMsgSourceType())) {
                    msgSourceVO.setMsgSourceTypeName(MsgSourceEnum.SMARTPUSH.getTypeName());
                }
                if (MsgSourceEnum.WARN.getValue().equals(msgSourceVO.getMsgSourceType())) {
                    msgSourceVO.setMsgSourceTypeName(MsgSourceEnum.WARN.getTypeName());
                }
            }
        }
        pageInfo.setList(msgSourceVOs);
        return pageInfo;
    }

    @Override
    public List<DepVo> listOwnerDept(MsgQuery msgQuery) {
        List<DepVo> depVos = new ArrayList();
        if (StringUtils.isNotBlank(msgQuery.getCreTimeStart())) {
            StringBuilder creTimeStart = new StringBuilder(msgQuery.getCreTimeStart());
            creTimeStart.append(DAY_START);
            msgQuery.setCreTimeStart(creTimeStart.toString());
        }
        if (StringUtils.isNotBlank(msgQuery.getCreTimeEnd())) {
            StringBuilder creTimeEnd = new StringBuilder(msgQuery.getCreTimeEnd());
            creTimeEnd.append(DAY_END);
            msgQuery.setCreTimeEnd(creTimeEnd.toString());
        }
        List<MsgSourceVO> msgSourceVOs = msgSourceMapper.list(msgQuery);
        if (null != msgSourceVOs && msgSourceVOs.size() > 0) {
            for (MsgSourceVO msgSourceVO : msgSourceVOs) {
                DepVo depVo = new DepVo();
                depVo.setOwnerDept(msgSourceVO.getOwnerDept());
                depVo.setOwnerDeptName(msgSourceVO.getOwnerDeptName());
                depVos.add(depVo);
            }
        }
        Iterator<DepVo> iterator = depVos.iterator();
        while (iterator.hasNext()) {
            DepVo depVo = iterator.next();
            if (StringUtils.isBlank(depVo.getOwnerDept()) || StringUtils.isBlank(depVo.getOwnerDeptName())) {
                iterator.remove();
            }
        }
        Set<DepVo> set = new HashSet();
        if (!CollectionUtils.isEmpty(depVos)) {
            for (DepVo depVo : depVos) {
                set.add(depVo);
            }
        }
        return new ArrayList(set);
    }

    @Override
    public List<DepVo> listOwnerDeptForMessage(MsgQuery msgQuery) {
        List<DepVo> depVos = new ArrayList();
        if (StringUtils.isNotBlank(msgQuery.getCreTimeStart())) {
            StringBuilder creTimeStart = new StringBuilder(msgQuery.getCreTimeStart());
            creTimeStart.append(DAY_START);
            msgQuery.setCreTimeStart(creTimeStart.toString());
        }
        if (StringUtils.isNotBlank(msgQuery.getCreTimeEnd())) {
            StringBuilder creTimeEnd = new StringBuilder(msgQuery.getCreTimeEnd());
            creTimeEnd.append(DAY_END);
            msgQuery.setCreTimeEnd(creTimeEnd.toString());
        }
        List<MsgSourceVO> msgSourceVOs = msgSourceMapper.queryMsgList(msgQuery);
        if (null != msgSourceVOs && msgSourceVOs.size() > 0) {
            for (MsgSourceVO msgSourceVO : msgSourceVOs) {
                DepVo depVo = new DepVo();
                depVo.setOwnerDept(msgSourceVO.getOwnerDept());
                depVo.setOwnerDeptName(msgSourceVO.getOwnerDeptName());
                depVos.add(depVo);
            }
        }
        Iterator<DepVo> iterator = depVos.iterator();
        while (iterator.hasNext()) {
            DepVo depVo = iterator.next();
            if (StringUtils.isBlank(depVo.getOwnerDept()) || StringUtils.isBlank(depVo.getOwnerDeptName())) {
                iterator.remove();
            }
        }
        Set<DepVo> set = new HashSet();
        if (!CollectionUtils.isEmpty(depVos)) {
            for (DepVo depVo : depVos) {
                set.add(depVo);
            }
        }
        return new ArrayList(set);
    }

    @Override
    public int deleteMsgSource(MsgQuery msgQuery) {
        //2020年8月19日 删除消息源，同时(逻辑)删除绑定的消息模板
        logger.info("删除消息源，先删除绑定消息渠道");
        MsgSourceVO msgSourceVO = msgSourceMapper.queryMsgSourceDetail(msgQuery);
        if (msgSourceVO.getMsgSourceId() != null) {
            logger.info("绑定消息模板,逻辑删除消息渠道关系");
            /*MessageTemplate query = new MessageTemplate().setTemplateCode(String.valueOf(msgSourceVO.getTemplateId()));
            MessageTemplate bindTemplate = messageTemplateMapper.queryByEntity(query);
            bindTemplate.setIsEnabled("N");
            messageTemplateMapper.update(bindTemplate);*/
            QueryWrapper<MsgSourceChannel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("msg_source_id", msgSourceVO.getMsgSourceId());
            List<MsgSourceChannel> msgSourceChannels = msgSourceChannelMapper.selectList(queryWrapper);
            for (MsgSourceChannel msgSourceChannel : msgSourceChannels) {
                msgSourceChannel.setIsDeleted("Y");
                msgSourceChannelMapper.updateById(msgSourceChannel);
            }
        }

        // 删除消息源
        int i = msgSourceMapper.delMsgSource(msgQuery.getMsgSourceId());

        if (i != 1) {
            throw new BaseException(CommonErrorCode.FAIL_DEL_MSGSOURCE);
        }
        return i;
    }

    @Override
    public List<MessageTypeVO> listMessageTypes() {
        List<MessageTypeVO> result = new ArrayList<>();

        List<String> wechatMessageTypeList = Arrays.asList("01", "02", "03", "04", "05", "06", "07");
        List<String> appMessageTypeList = Arrays.asList("01", "02", "03");
        List<String> pageClientTypeList = Arrays.asList("01", "02", "03");
        List<String> smsTypeList = Arrays.asList("01");
        List<String> emailTypeList = Arrays.asList("01", "02", "03", "08");
        List<String> systemTypeList = Arrays.asList("01");
        List<String> dingTalkTypeList = Arrays.asList("01");
        //2020年5月25日 这块写得也太随意了

        List<String> alipayAppletTypeList = Arrays.asList("01");
        List<String> wechatAppletTypeList = Arrays.asList("01");
        List<String> mailTypeList = Arrays.asList("01");
        List<String> mpaasTypeList = Arrays.asList("01");

        List<String> newSmsTypeList = Arrays.asList("01");

        DecimalFormat channelTypeStringFormat = new DecimalFormat("00");

        String channelTypeStr = channelTypeStringFormat.format(ChannelTypeEnum.DYSMS.getType());
        result.addAll(generateMessageTypeList(ChannelTypeEnum.DYSMS.getType(), channelTypeStr, smsTypeList));

        channelTypeStr = channelTypeStringFormat.format(ChannelTypeEnum.SYSTEM.getType());
        result.addAll(generateMessageTypeList(ChannelTypeEnum.SYSTEM.getType(), channelTypeStr, systemTypeList));

        channelTypeStr = channelTypeStringFormat.format(ChannelTypeEnum.DING_TALK.getType());
        result.addAll(generateMessageTypeList(ChannelTypeEnum.DING_TALK.getType(), channelTypeStr, dingTalkTypeList));

        channelTypeStr = channelTypeStringFormat.format(ChannelTypeEnum.DING_ROBOT.getType());
        result.addAll(generateMessageTypeList(ChannelTypeEnum.DING_ROBOT.getType(), channelTypeStr, dingTalkTypeList));

        channelTypeStr = channelTypeStringFormat.format(ChannelTypeEnum.DING_COMPANY_GROUP.getType());
        result.addAll(generateMessageTypeList(ChannelTypeEnum.DING_COMPANY_GROUP.getType(), channelTypeStr, dingTalkTypeList));

        channelTypeStr = channelTypeStringFormat.format(ChannelTypeEnum.ALIPAY_APPLET.getType());
        result.addAll(generateMessageTypeList(ChannelTypeEnum.ALIPAY_APPLET.getType(), channelTypeStr, alipayAppletTypeList));

        channelTypeStr = channelTypeStringFormat.format(ChannelTypeEnum.WECHAT_APPLET.getType());
        result.addAll(generateMessageTypeList(ChannelTypeEnum.WECHAT_APPLET.getType(), channelTypeStr, wechatAppletTypeList));

        channelTypeStr = channelTypeStringFormat.format(ChannelTypeEnum.MAIL.getType());
        result.addAll(generateMessageTypeList(ChannelTypeEnum.MAIL.getType(), channelTypeStr, mailTypeList));

      /*  channelTypeStr = channelTypeStringFormat.format(ChannelTypeEnum.NEW_SMS.getValue());
        result.addAll(generateMessageTypeList(ChannelTypeEnum.NEW_SMS.getValue(), channelTypeStr, newSmsTypeList));*/

        channelTypeStr = channelTypeStringFormat.format(ChannelTypeEnum.MPAAS.getType());
        result.addAll(generateMessageTypeList(ChannelTypeEnum.MPAAS.getType(), channelTypeStr, mpaasTypeList));

        return result;
    }

    @Override
    public Page<MsgSourceVO> smsMsgSourceList(MsgQuery msgQuery) {
        return msgSourceMapper.list(msgQuery);
    }

    private List<MessageTypeVO> generateMessageTypeList(int channelType, String channelTypeStr, List<String> messageTypeList) {
        List<MessageTypeVO> result = new ArrayList<>();
        Map<String, String> messageTypeNameMap = new HashMap<>(16);
        messageTypeNameMap.put("01", "文本消息");
        messageTypeNameMap.put("02", "图片消息");
        messageTypeNameMap.put("03", "图文消息");
        messageTypeNameMap.put("04", "语音消息");
        messageTypeNameMap.put("05", "视频消息");
        messageTypeNameMap.put("06", "文件消息");
        messageTypeNameMap.put("07", "文本卡片");
        messageTypeNameMap.put("08", "超链接");

        for (String messageType : messageTypeList) {
            MessageTypeVO messageTypeVO = new MessageTypeVO();
            String stringBuilder = channelTypeStr +
                    messageType;
            messageTypeVO.setPushChannelType(channelType)
                    .setMessageTypeName(messageTypeNameMap.get(messageType))
                    .setMessageType(stringBuilder);
            result.add(messageTypeVO);
        }

        return result;
    }

    /**
     * 消息源绑定消息模板（实际为在模板列表中，添加消息源UUID作为关联绑定）
     *
     * @param templateId  模板主键id
     * @param msgSourceId 消息源UUID
     */
    private void msgSourceBindTemplate(Long templateId, String msgSourceId) {
        /*logger.info("创建消息源进行绑定消息模板逻辑入参：模板主键id：{},消息源UUID:{}", templateId, msgSourceId);
        if (StringUtils.isBlank(msgSourceId)) {
            return;
        }
        MessageTemplate query;
        MsgSource msgSource;
        if (templateId == null) {
            logger.info("模板主键ID为空");
            logger.info("更新消息源中的是否使用模板字段为:不使用");
            msgSource = new MsgSource();
            msgSource.setSourceId(msgSourceId);
            msgSource.setTemplateActive(0);
            msgSourceMapper.modMsgSource(msgSource);
            logger.info("模板列表关联UUID置空");
            *//*query = new MessageTemplate().setMsgSourceId(msgSourceId);
            MessageTemplate messageTemplate = messageTemplateMapper.queryByEntity(query);
            if (messageTemplate != null) {
                messageTemplate.setMsgSourceId(null);
                messageTemplateMapper.update(messageTemplate);
            }*//*
        } else {
            logger.info("模板主键ID不为空");
            logger.info("更新消息源中的是否使用模板字段为:使用");
            msgSource = new MsgSource();
            msgSource.setSourceId(msgSourceId);
            msgSource.setTemplateActive(1);
            msgSourceMapper.modMsgSource(msgSource);
            logger.info("更新模板列表关联UUID");
            query = new MessageTemplate().setTemplateId(templateId);
            //能选到的模板(包括原来绑定的模板)，所以查询到模板中关联的UUID不一定为空。这种情况只在修改时产生
            MessageTemplate unbindTemplate = messageTemplateMapper.queryByEntity(query);
            //查询该消息源已经绑定的消息模板
            MessageTemplate queryBind = new MessageTemplate().setMsgSourceId(msgSourceId);
            MessageTemplate bindTemplate = messageTemplateMapper.queryByEntity(queryBind);
            if (bindTemplate == null) {
                logger.info("该消息源原来未绑定模板，直接更新绑定");
                unbindTemplate.setMsgSourceId(msgSourceId);
                messageTemplateMapper.update(unbindTemplate);
            } else {
                logger.info("该消息源已绑定过模板");
                if (StringUtils.equals(unbindTemplate.getMsgSourceId(), msgSourceId)) {
                    logger.info("该消息源消息模板前后一致，不做修改");
                } else {
                    logger.info("该消息源更换消息模板");
                    logger.info("释放旧模板");
                    bindTemplate.setMsgSourceId(null);
                    messageTemplateMapper.update(bindTemplate);
                    logger.info("绑定新模板");
                    unbindTemplate.setMsgSourceId(msgSourceId);
                    messageTemplateMapper.update(unbindTemplate);
                }
            }
        }*/
    }

    @Override
    public MsgSource getMsgSourceBySourceId(String sourceId) {
        return msgSourceMapper.queryBySourceId(sourceId);
    }

    @Override
    public MsgSource getMsgSourceBySourceCode(String sourceCode) {
        return msgSourceMapper.getMsgSourceBySourceCode(sourceCode);
    }

    @Override
    public Integer updateStatus(MsgSourceDto msgSourceDto) {
        return msgSourceMapper.updateStatus(msgSourceDto);
    }

    @Override
    public List<PushChannelInfo> getPushChannelByMsgSourceId(Long msgSourceId) {
        return pushChannelRepository.getPushChannelByMsgSourceId(msgSourceId);
    }

    @Override
    public MsgSource getMsgSource(MsgQuery qry) {
        return msgSourceMapper.getMsgSource(qry);
    }

    @Override
    public Integer selectMsgSourceIdByMessageCode(String messagecode) {
        return msgMapper.selectMsgSourceIdByMessageCode(messagecode);
    }

    @Override
    @PagingAnnotation
    public Object noSpecifiedBaseMessageSourcelist(BaseMessageSourceQuery baseMessageSourceQuery) {
        List<BaseMessageSourceEntity> list = msgMapper.noSpecifiedBaseMessageSourcelist(baseMessageSourceQuery);
        if (CollectionUtils.isEmpty(list)) {
            return new PageInfo<>();
        }
        PageInfo pageInfo = new PageInfo(list);
        pageInfo.setList(list);
        return pageInfo;
    }
}
